package com.parking.status.sync.netty.service;

import com.parking.status.sync.entity.CommandBase;
import com.parking.status.sync.netty.client.TcpClient;
import com.parking.status.sync.netty.entity.RequestPre;
import com.parking.status.sync.netty.entity.RequestSyncParkingInfo;
import com.parking.status.sync.netty.entity.ResponsePre;
import com.parking.status.sync.netty.event.ResponseReceivedEvent;
import com.parking.status.sync.netty.event.ResponseReceivedEventParameters;
import com.parking.status.sync.repository.CommandBaseRepository;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;

/**
 * Created by Administrator on 2015/9/18.
 */
@Component
public class ResponseReceivedEventListener implements ApplicationListener<ResponseReceivedEvent> {

    @Autowired
    CommandFactory commandFactory;

//    @Autowired
//    TcpClient tcpClient;

    @Autowired
    RequestFactory requestFactory;

    @Override
    @Transactional
    public void onApplicationEvent(ResponseReceivedEvent responseReceivedEvent) {
        //TODO 收到回复后再发送一个请求
        ResponseReceivedEventParameters param = (ResponseReceivedEventParameters)responseReceivedEvent.getSource();
        ResponsePre response = param.getResponsePre();
        ChannelHandlerContext context = param.getContext();

        //TODO 逻辑处理在这里
        CommandBaseRepository commandBaseRepository = commandFactory.getCommandRepository(response.getClass());
        commandBaseRepository.updateStatus(response.getSeqno());

//        //再发一个请求
//        RequestSyncParkingInfo info = new RequestSyncParkingInfo();
//        info.forTest();
//        context.channel().writeAndFlush(info);

        try {
            CommandBase command = commandFactory.createCommandFromDB();
            RequestPre info = requestFactory.createRequestByCommand(command);
            context.channel().writeAndFlush(info);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
